﻿using System.Linq;
using UnityEngine;

public class CircleMan : CircleArea
{
    private float m_xmin;
    private float m_xmax;
    private float m_zmin;
    private float m_zmax;
    private float m_xwidth;
    private float m_zwidth;

    public Transform[] Cams;

    public float Speed;
    public float Angle;

    protected override void OnChange()
    {
        var lst = Cams.ToList();
        lst.Sort((x1, x2) =>
        {
            var len1 = Vector3.Distance(x1.position, transform.position);
            var len2 = Vector3.Distance(x2.position, transform.position);
            return len1.CompareTo(len2);
        });
        for (int i = 0; i < lst.Count; i++)
        {
            lst[i].GetComponent<Camera>().depth = -i;
        }
        //var min = float.MaxValue;
        //int index = 0;
        //for (var i = 0; i < Cams.Length; i++)
        //{
        //    var cam = Cams[i];
        //    var dis = Vector3.Distance(cam.position, transform.position);
        //    if (dis < min)
        //    {
        //        min = dis;
        //        index = i;
        //    }
        //}
        //var ord = (index + 2)%Cams.Length;
        //Cams[index].GetComponent<Camera>().cullingMask = -1;
        //Cams[ord + 2].GetComponent<Camera>().cullingMask = -3;
    }

    public void Move(Vector3 dir)
    {
        Debug.Log("move:"+dir);
        transform.position += (dir * Speed * Time.deltaTime);
        foreach (var cam in Cams)
        {
            //cam.position += (dir * Speed * Time.deltaTime);
        }
    }

    public void Rotate(Vector3 euler)
    {
        Debug.Log("rot:"+ euler);
        transform.Rotate(euler * Angle * Time.deltaTime);
        foreach (var cam in Cams)
        {
            //cam.Rotate(euler * Angle * Time.deltaTime);
        }
    }

    public override float Xmin
    {
        get { return m_xmin; }
    }

    public override float Xmax
    {
        get { return m_xmax; }
    }

    public override float Zmin
    {
        get { return m_zmin; }
    }

    public override float Zmax
    {
        get { return m_zmax; }
    }

    public override float Xwidth
    {
        get { return m_xwidth; }
    }

    public override float Zwidth
    {
        get { return m_zwidth; }
    }

    internal void Awake()
    {
        var camTerrain = Terrain.activeTerrain;
        var ori = camTerrain.transform.position;
        m_xwidth = camTerrain.terrainData.size.x;
        m_zwidth = camTerrain.terrainData.size.z;
        m_xmin = ori.x;
        m_xmax = ori.x + m_xwidth;
        m_zmin = ori.z;
        m_zmax = ori.x + m_zwidth;

        OnChange();
    }
}